#include "Render.h"
#include <GLFW/glfw3.h>

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

#include <assert.h>

#include "VertexBuffer.h"
#include "IndexBuffer.h"
#include "VertexArray.h"

struct ShaderSourceCode {
    std::string VertexSource;
    std::string FragmentSource;
};

static ShaderSourceCode ParseShader(const std::string& shaderFilePath) {
    std::ifstream shaderFile(shaderFilePath);

    enum ShaderType {
        None = -1,
        Vertex = 0,
        Fragment = 1
    };

    ShaderType type = None;

    std::stringstream ss[2];
    std::string line;
    while (std::getline(shaderFile, line)) {
        if (line.find("#shader") != std::string::npos) {
            if (line.find("vertex") != std::string::npos)
                type = Vertex;
            else if (line.find("fragment") != std::string::npos)
                type = Fragment;
        }

        else {
            if (type != None)
                ss[(int)type] << line << '\n';
        }
    }


    return { ss[0].str(), ss[1].str() };
}

static unsigned int ComplieShader(unsigned int type, const std::string& shaderSourceCode) {
    unsigned int id = glCreateShader(type);
    const char* source = shaderSourceCode.c_str();
    glShaderSource(id, 1, &source, nullptr);

    //after compile shader, we can retrieve the state by using glGetShader
    glCompileShader(id);

    //Error handling
    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE) {
        int errorMsgLen;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &errorMsgLen);

        //在栈上动态分配内存
        char* message = (char*)alloca(size_t(errorMsgLen) * sizeof(char));

        glGetShaderInfoLog(id, errorMsgLen, &errorMsgLen, message);
        std::cout << "Failed to compile shader: " << message << std::endl;
        
        glDeleteShader(id);
        return 0;
    }


    return id;
}

static unsigned int CreateShader(const std::string& vertexShader, const std::string& fragmentShader) {
    unsigned int program = glCreateProgram();
    unsigned int vs = ComplieShader(GL_VERTEX_SHADER, vertexShader);
    unsigned int fs = ComplieShader(GL_FRAGMENT_SHADER, fragmentShader);

    //attach
    glAttachShader(program, vs);
    glAttachShader(program, fs);

    //link
    glLinkProgram(program);

    //will be stored as part of the program object's state, and then can retrieve it
    glValidateProgram(program);

    //delete intermediate, but not necessary
    glDeleteShader(vs);
    glDeleteShader(fs);

    return program;
}

int main(void)
{
    GLFWwindow* window;
	
    /* Initialize the library */
    if (!glfwInit())
        return -1;

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    /* glew init */
    if (glewInit() != GLEW_OK)
        return -1;

	/* vertex buffer */
    float positions[] = {
        -0.5f, -0.5f,	// 0
         0.5f, -0.5f,	// 1
         0.5f,  0.5f,	// 2
		-0.5f,  0.5f,	// 3
    };


	VertexBuffer vb(positions, sizeof(float) * 4 * 2);

	VertexBufferLayout vbl;
	vbl.Push<float>(2);

	VertexArray va;
	va.AddBuffer(vb, vbl);

	//GLuint vao;
	//glGenVertexArrays(1, &vao);
	//glBindVertexArray(vao);

	//GLCALL(glEnableVertexAttribArray(0));
	//GLCALL(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0));

	/* indices buffer */
	unsigned int indices[] = {
		0, 1, 2,
		2, 3, 0
	};

	IndexBuffer ib(indices, 6);

    ShaderSourceCode shaders = ParseShader(RESOURCE_DIRECTORY "/Shaders/Basic.shader");
    unsigned int shader = CreateShader(shaders.VertexSource, shaders.FragmentSource);
    glUseProgram(shader);

    int location = glGetUniformLocation(shader, "u_Color");
    glUniform4f(location, 1.0f, 1.0f, 0.0f, 1.0f);

    float rBuffer = 1.0f;
    float increment = 0.05f;

    glUseProgram(0);
	glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader);
        glUniform4f(location, rBuffer, 1.0f, 0.0f, 1.0f);

		va.Bind();

		ib.Bind();
        //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

		GLCALL(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr));

        if (rBuffer > 1.0f)
            increment = -0.05f;
        else if (rBuffer < 0.0f)
            increment = 0.05f;

        rBuffer += increment;

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }
    
    glDeleteProgram(shader);

    glfwTerminate();
    return 0;
}